const { getList, getDetail, newBlog, updateBlog, delBlog } = require('../controller/blog')
const { SuccessModel, ErrorModel } = require('../model/resModel')


// 统一的登录验证函数   返回undefined说明登录，返回对象说明未登录
const loginCheck = (req) => {
    if (!req.session.username) {
        return Promise.resolve(
            new ErrorModel('尚未登录')
        )
    }
}

async function handleBlogRouter(req, res) {
    const method = req.method // GET POST
    const id = req.query.id

    // 获取博客列表
    if (method === 'GET' && req.path === '/api/blog/list') {
        const author = req.query.author || ''
        const keyword = req.query.keyword || ''
        // 返回了一个查询对象   RowDataPacket对象：RowDataPacket{data:[{...}, {...}, {...}]}
        let result = await getList(author, keyword)
        result = _object2JSON(result)
        // JSON.stringify()方法 拿到里面的普通对象数据，并字符串化普通对象数据: { data:[{...}, {...}, {...}] }
        // result = JSON.stringify(result)
        // 转化为json对象：{ "data" : "[{...}, {...}, {...}]" }
        // result = JSON.parse(result)
        // if (!result) {
        //     return new ErrorModel('没有元素')
        // }
        // 查不到元素会返回空数组，状态应该还是成功的，表示查到一个空集
        // 因为用的是async/await，所以返回这个success对象会被promise包装一下，所以还是返回的promise，要在上一层继续解剖promise拿到这个对象
        return new SuccessModel(result)
    }
    // 获取博客详情
    if (method === 'GET' && req.path === '/api/blog/detail') {
        let result = await getDetail(id)
        result = _object2JSON(result)
        // console.log(result[0])
        return new SuccessModel(result[0])
    }
    // 新建一篇博客
    if (method === 'POST' && req.path === '/api/blog/new') {
        const loginCheckResult = loginCheck(req)
        if (loginCheckResult) {
            // 未登录
            return loginCheckResult
        }
        /*OkPacket {
            fieldCount: 0,
            affectedRows: 1,
            insertId: 5,
            serverStatus: 2,
            warningCount: 0,
            message: '',
            protocol41: true,
            changedRows: 0 }*/
        req.body.author = req.session.username 
        let result = await newBlog(req.body)
        result = _object2JSON(result)
        return new SuccessModel({ id: result.insertId })
    }

    // 更新一篇博客
    if (method === 'POST' && req.path === '/api/blog/update') {
        const loginCheckResult = loginCheck(req)
        if (loginCheckResult) {
            // 未登录
            return loginCheckResult
        }
        let result = await updateBlog(id, req.body)
        if (result) {
            return new SuccessModel()
        } else {
            return new ErrorModel('更新博客失败')
        }
    }

    // 删除一篇博客
    if (method === 'POST' && req.path === '/api/blog/del') {
        const loginCheckResult = loginCheck(req)
        if (loginCheckResult) {
            // 未登录
            return loginCheckResult
        }
        const author = req.session.username
        const result = await delBlog(id, author)
        if (result) {
            return new SuccessModel()
        } else {
            return new ErrorModel('删除博客失败')
        }
    }
}

function _object2JSON(listData) {
    return JSON.parse(JSON.stringify(listData))
}

module.exports = handleBlogRouter
